import React, { useMemo } from 'react';
import {
  useNodeStore,
  useConnectionStore,
  CodeCompiler,
  useVariableStore,
} from 'codeck';
import { Notification } from '@arco-design/web-react';
import { useRegistryStore } from '@/registry/store';
let code = '';
export const EduCodeEditor: React.FC = React.memo(() => {

  const { nodeMap, nodeDefinition } = useNodeStore((state) => ({
    nodeMap: state.nodeMap,
    nodeDefinition: state.nodeDefinition,
  }));
  const connections = useConnectionStore((state) => state.connections);
  const variableMap = useVariableStore((state) => state.variableMap);
  const inited = useRegistryStore((state) => state.inited);

  useMemo(() => {
    try {
      const text = new CodeCompiler().generate();
      if (code != text) {
        window.parent.postMessage({ "type": "nodaCode", "code": text }, '*');
        code = text;
      }
    } catch (err) {
      console.warn(err);
      Notification.error({
        id: 'codeErroe',
        style: { width: 500 },
        title: '代码编译出错',
        content:
          '节点编译成代码失败，请检查节点。具体错误请查看控制台',
      })
    }

  }, [nodeMap, nodeDefinition, connections, variableMap, inited]);
  return (<></>);
});
EduCodeEditor.displayName = 'EduCodeEditor';


